<template>
  <div class="import-container">
    <el-dialog
      title="导入接警人"
      :visible.sync="dialogVisible"
      width="600px"
      :before-close="closeAddDialog"
      :append-to-body="true"
      :close-on-click-modal="false"
    >
      <div class="mini-dialog">
        <h3 class="title" style="margin-top: 5px">导入文件编辑注意事项：</h3>
        <div class="import-item">1、 已存在接警人无法导入</div>
        <div class="import-item">
          2、请在对应单元格填写接警人名称、接警人手机号等。
        </div>
        <div class="import-item">
          3、Excel输入单元格内不能出现中文、特殊符号及空格
        </div>
      </div>

      <el-form
        :model="addInfo"
        class="demo-form-inline"
        :rules="rules"
        ref="ruleForm"
        label-width="80px"
      >
        <el-form-item style="width: 100%" prop="parentId" label="组织机构">
          <TreeSearchAdd
            style="width: 100%"
            @changeOrgId="changeOrgId"
            @onClear="onClear"
            ref="refTreeSearchAdd"
            :clearable="false"
          >
          </TreeSearchAdd>
        </el-form-item>

        <el-form-item size="small" label="联网单位" prop="orgId">
          <el-select size="small" style="width: 100%;" clearable v-model='addInfo.orgId'
            placeholder='请选择' filterable >
            <el-option v-for='item in orgList' :label='item.orgName' :value='item.id' :key='item.id'>
            </el-option>
          </el-select>
        </el-form-item>
                
      </el-form>

      <div class="content">
        <div>
          <div class="btn-row">
            <el-upload
              ref="upload"
              action="#"
              :limit="1"
              accept=".xls,.xlsx"
              :multiple="false"
              :before-upload="beforeUpload"
              :on-change="handChange"
              :on-exceed="handleExceed"
              :auto-upload="false"
              :http-request="uploadRequest"
            >
              <el-button slot="trigger" size="small" type="primary">
                选取文件
              </el-button>
              <el-button size="small" type="info" @click="handleDownload">
                下载模板
              </el-button>
              <div class="el-upload__tip" slot="tip">
                只能上传Excel文件，且不超过500kb
              </div>
            </el-upload>
          </div>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button
          slot="trigger"
          size="small"
          type="primary"
          @click="importStart"
        >
          开始导入
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { reqReceiverImport, reqOrgList } from "@api/api";
import { mapState } from "vuex";
import selectLoadMore from "@/components/select-load-more.vue"; //下拉加载
import TreeSearchAdd from "@components/TreeSearchAdd.vue";

export default {
  name: "importDevice",
  props: ["getLocationInfo", "getAddressflag"],
  components: { selectLoadMore, TreeSearchAdd },
  data() {
    return {
      dialogVisible: false,
      isXlsx: true,
      /* mini弹框 */
      addInfo: {
        orgId: null,
        parentId:""
      },
      productList: [],
      rules: {
        parentId: [
          {
            required: true,
            message: "请选择组织机构",
            trigger: ["blur", "change"],
          },
        ],
        orgId: [
          {
            required: true,
            message: "请选择联网单位",
            trigger: ["blur", "change"],
          },
        ],
      },

      sysInstanceTotalPages: 10,
      projectList: [], //组织机构数据
      orgList:[],
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  watch: {
    dialogVisible(e) {
      if (e) {
        this.$nextTick(() => {
          this.$refs.refTreeSearchAdd.getDataList();
        });
      }
    },
  },
  methods: {
    changeOrgId(instanceId) {
      this.addInfo.parentId = instanceId.id
      this.addInfo.orgId=''
      this.getOrgList();
    },
        // 请求单位列表
        async getOrgList() {
      let { tenantId, userId, roleName } = this.user;
      const res = await reqOrgList({
        tenantId,
        userId,
        roleName,
        orgName: this.orgName,
        parentId: this.addInfo.parentId,
        type: "4"
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.orgList = res.data.rows
    },
    onClear() {
      this.addInfo.orgId = "";
    },
    // 获取组织机构列表
    async OrgList(msg) {
      var res = await reqOrgList({
        userId: this.user.userId,
        roleName: this.user.roleName,
        tenantId: this.user.tenantId,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      // this.sysInstanceTotalPages = res.data.total;
      // this.projectList = [
      //   ...this.projectList,
      //   ...JSON.parse(
      //     JSON.stringify(res.data.rows).replace(/orgName/g, "names")
      //   ),
      // ]; // 修改数组中对象的属性名
      this.projectList = res.data.rows
    },
    // 下拉 组织机构
    visibleChangeCompany(msg) {
      if (msg.val && this.projectList.length <= 0) {
        this.OrgList(msg);
      }
    },
    // 上传前验证
    beforeUpload(file) {
      let Xls = file.name.split(".");
      if (Xls[1] !== "xls" || Xls[1] !== "xlsx") {
        this.isXlsx = false;
      }
    },
    // 因为 before-upload 是指在文件上传之前、文件已被选中，但还没上传的时候触发，而设置了 :auto-upload=“false” 后，文件上传事件不被再次调用，所以 before-upload 不生效，所以，限制大小的时候，需绑定在 :on-change 里面
    handChange(file) {
      const limitSize = file.size / 1024 / 1024;
      if (limitSize > 0.5) {
        this.$refs.upload.clearFiles();
        this.$modal.notifyWarning("上传文件大小不能超过 500KB!");
        return false;
      }
      let Xls = file.name.split(".");
      if (Xls[1] !== "xls" && Xls[1] !== "xlsx") {
        this.$refs.upload.clearFiles();
        this.$modal.notifyWarning("只能上传Excel文件!");
      }
    },
    handleExceed() {
      this.$modal.notifyWarning(`当前限制选择 1 个文件`);
    },
    // 自定义上传
    async uploadRequest(param) {
      const formData = new FormData();
      formData.append("file", param.file);
      formData.append("orgId", this.addInfo.orgId);
      const loading = this.$loading({
        lock: true,
        text: "正在导入，请耐心等待~",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.7)",
      });
      const res = await reqReceiverImport(
        formData
        // , {
        //   orgId: this.addInfo.orgId,
        // }
      );
      loading.close();
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      setTimeout(() => {
        this.$modal.notifySuccess("导入成功");
        this.closeAddDialog();
        this.$parent.getInitDataList();
      }, 500);
    },
    handleDownload() {
      // location.href =
      //   "https://huhutong2020.oss-cn-shenzhen.aliyuncs.com/2021/12/24/e1908bf30da2498c84b01be61cbe00ff.xls";
      var self = this;
      import("../../../vendor/Export2Excel").then((excel) => {
        const tHeader = [
          "*接警人名称",
          `*接警人手机号`,
          "公众号接收（1开 0关）",
          "短信接收（1开 0关）",
          "语音接收（1开 0关）",
        ];
        const filterVal = [
          "name",
          "mobile",
          "mpReceive",
          "msgReceive",
          "mobileReceive",
        ];
        const list = [
          {
            name: "刘某",
            mobile: "15526276124",
            mpReceive: "1",
            msgReceive: "0",
            mobileReceive: "0",
          },
          {
            name: "李某",
            mobile: "15526276125",
            mpReceive: "1",
            msgReceive: "1",
            mobileReceive: "1",
          },
        ];
        const data = self.formatJson(filterVal, list);

        excel.export_json_to_excel({
          header: tHeader, //表头
          data, //json数据
          filename: "导入模板", //导出文件名
          autoWidth: true, //宽度是否自适应
          bookType: "xlsx", //导出文件后缀名
        });
      });
      this.miniDialogVisible = false;
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          return v[j];
        })
      );
    },
    // 正式上传
    importStart() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.$refs.upload.submit();
        }
      });
    },
    // 点击关闭大弹框
    closeAddDialog() {
      this.$refs.ruleForm.resetFields();
      this.dialogVisible = false;
      this.addInfo.orgId = "";
      // this.$refs.refLoadMore.value = "";
      this.$refs.upload.clearFiles();
      if (this.$refs.refTreeSearchAdd) {
        this.$refs.refTreeSearchAdd.onclose(); //清空组织机构
      }
    },
  },
  deactivated() {
    if (this.$refs.ruleForm != null) {
      this.closeAddDialog();
    }
  },
};
</script>

<style lang="less" scoped>
@import url("../../common.less");

.mini-dialog {
  margin: 10px 0 20px 24px;
  color: @primaryThemeTxtColor;
}
.el-upload__tip {
  color: @primaryThemeTxtColor;
}

.content {
  padding-left: 21px;
  width: 350px;
  position: relative;
  top: 0;
  bottom: 0;
  left: 20px;
  right: 0;

  // 按钮行
  .btn-row {
    .el-button {
      margin-right: 20px;
    }
  }
}

/* mini弹框 */
.title {
  line-height: 30px;
}

.import-item {
  line-height: 24px;
}

::v-deep .el-collapse {
  border: none;
}

::v-deep .el-icon-arrow-right {
  color: @primaryThemeTxtColor;
}

::v-deep .el-input__inner {
  height: 32px !important;
}

form {
  padding-left: 40px !important;
}

.zuobiao {
  color: @primaryTxtcolor !important;
}

::v-deep .el-form-item {
  margin-bottom: 18px;
  margin-right: 0px;
}

.mapLoc {
  height: 60vh;
  width: 100%;
  overflow-y: hidden;

  .iframe {
    width: 100%;
    height: 100%;
  }
}
</style>
